package softtech.apps.callblocker;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.android.internal.telephony.ITelephony;

import softtech.apps.utility.ApplicationConstants;
import softtech.apps.callblocker.adapter.AdapterCallMode;
import softtech.apps.callblocker.adapter.AdapterSmsMode;
import softtech.apps.callblocker.model.BlackListItem;
import softtech.apps.callblocker.model.CallBlockedItem;
import softtech.apps.callblocker.model.DatabaseHanler;
import softtech.apps.callblocker.model.SmsBlockedItem;
import android.animation.AnimatorSet.Builder;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class ActivityContactProfile extends Activity {

	protected static final String TAG = null;

	private Context mContext = this;
	// variant to check position of Viewflipper
	int posInViewFlipper = 1;

	/*
	 * bien de kiem tra trang thai nut Edit hoac save
	 */
	private int checkClick = 1;

	private ImageView imgProfile;
	private ImageView imgEditPhone;
	private ImageView imgCallBack;
	private ImageView imgSendBack;

	private TextView tvNameProfile;
	private TextView tvPhoneProfile;
	private TextView tvCallBlocked;
	private TextView tvSmsBlocked;
	private TextView tvTimeCallBlocked;
	private TextView tvTimeSmsBlocked;

	private EditText edtEditPhone;
	private EditText edtEditName;

	private Button btnLastBlocked;
	private Button btnModeCall;
	private Button btnModeSms;

	private ListView lvModeCall;
	private ListView lvModeSms;

	private ViewFlipper viewFlipper;
	/**
	 * layout contain edtEdtiPhone
	 */
	private LinearLayout layoutEditPhone;
	/**
	 * layout contain edtEditName
	 */
	private LinearLayout layoutEditName;

	private AdapterSmsMode adaperSmsMode;
	private AdapterCallMode adapterCallMode;
	/**
	 * List<BlackListItem> containt BlackListITem in data
	 */
	List<BlackListItem> list = new ArrayList<BlackListItem>();

	private DatabaseHanler db = new DatabaseHanler(this);
	private BlackListItem item;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		setContentView(R.layout.activity_view_profile);
		getFormWidget();
		getEvent();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			break;
		case R.id.action_delete:
			showAlertDialog(
					mContext.getResources().getString(
							R.string.title_alert_dialog1),
					mContext.getResources().getString(
							R.string.message_alert_dialog3));

			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void deleteProFile() {
		// TODO Auto-generated method stub
		db.deleteBlackListItem(BlackListItem.ID + " = " + item.getId(), null);
		Intent i = new Intent(mContext, ActivityShowBlackListItem.class);
		startActivity(i);
		ActivityContactProfile.this.finish();

	}

	public void getFormWidget() {
		DatabaseHanler db = new DatabaseHanler(this);

		// get intent from ActivityShowBlackList
		Intent i = getIntent();
		Bundle bundle = i.getBundleExtra("bundle");
		item = (BlackListItem) bundle.getSerializable("item");
		if (item.getName().equals("")) {
			setTitle(this.getResources().getString(R.string.view_profile));
		} else {
			setTitle(item.getName());
		}

		imgProfile = (ImageView) findViewById(R.id.imgProfile);
		imgEditPhone = (ImageView) findViewById(R.id.imgEditPhone);
		imgCallBack = (ImageView) findViewById(R.id.imgCallBack);
		imgSendBack = (ImageView) findViewById(R.id.imgSendBack);

		layoutEditPhone = (LinearLayout) findViewById(R.id.layoutEditPhone);
		layoutEditName = (LinearLayout) findViewById(R.id.layoutEditName);

		tvNameProfile = (TextView) findViewById(R.id.tvNameProfile);
		tvPhoneProfile = (TextView) findViewById(R.id.tvPhoneProfile);
		tvCallBlocked = (TextView) findViewById(R.id.tvLastCallBlocked);
		tvSmsBlocked = (TextView) findViewById(R.id.tvLastSmsBlocked);
		tvTimeCallBlocked = (TextView) findViewById(R.id.tvTimeLastCallBlocked);
		tvTimeSmsBlocked = (TextView) findViewById(R.id.tvTimeLastSmsBlocked);

		edtEditPhone = (EditText) findViewById(R.id.edtEditPhone);
		edtEditPhone.setText(item.getPhoneNumber());
		edtEditName = (EditText) findViewById(R.id.edtEditName);
		edtEditName.setText(item.getName());

		btnLastBlocked = (Button) findViewById(R.id.btnLastBlocked);
		btnModeCall = (Button) findViewById(R.id.btnModeCall);
		btnModeSms = (Button) findViewById(R.id.btnModeSms);

		lvModeCall = (ListView) findViewById(R.id.lvModeCall);
		lvModeSms = (ListView) findViewById(R.id.lvModeSms);

		viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);

		tvNameProfile.setText(item.getName());
		tvPhoneProfile.setText(item.getPhoneNumber());

		// find in database last call blocked of number
		List<CallBlockedItem> listCallBlocked = new ArrayList<CallBlockedItem>();

		// find in database last sms blocked of this number
		List<SmsBlockedItem> listSms = new ArrayList<SmsBlockedItem>();

		if (item.getPhoneNumber().contains("+")) {
			listSms = db.getSmsBlockItem(null, SmsBlockedItem.PHONE_NUMBER
					+ " LIKE ? ", new String[] { item.getPhoneNumber()
					.substring(4) }, SmsBlockedItem.DATE_TIME + " DESC", String
					.valueOf(1));
			listCallBlocked = db.getCallBlockItem(null,
					CallBlockedItem.PHONE_NUMBER + " LIKE ? ",
					new String[] { item.getPhoneNumber().substring(4) },
					CallBlockedItem.DATE_TIME + " DESC", String.valueOf(1));
		} else {
			listSms = db.getSmsBlockItem(null, SmsBlockedItem.PHONE_NUMBER
					+ " LIKE ?", new String[] { "%" + item.getPhoneNumber()
					+ "%" }, SmsBlockedItem.DATE_TIME + " DESC",
					String.valueOf(1));
			listCallBlocked = db.getCallBlockItem(null,
					CallBlockedItem.PHONE_NUMBER + " LIKE ?",
					new String[] { "%" + item.getPhoneNumber() + "%" },
					CallBlockedItem.DATE_TIME + " DESC", String.valueOf(1));
		}
		if (listCallBlocked.size() > 0) {
			CallBlockedItem callBlocked = listCallBlocked.get(0);
			if (!callBlocked.getDate_time().equals(null)) {
				tvTimeCallBlocked.setText(callBlocked.getDate_time());
				tvCallBlocked.setText(callBlocked.getPhoneNumber());
			} else {
				tvCallBlocked.setText(getResources().getString(R.string.empty));
			}

		} else {
			tvCallBlocked.setText(getResources().getString(R.string.empty));
		}

		if (listSms.size() > 0) {
			SmsBlockedItem smsBlocked = listSms.get(0);
			if (!smsBlocked.getDate_time().equals(null)) {
				tvTimeSmsBlocked.setText(smsBlocked.getDate_time());
				tvSmsBlocked.setText(item.getPhoneNumber());
			} else {
				tvSmsBlocked.setText(getResources().getString(R.string.empty));
			}
		} else {
			tvSmsBlocked.setText(getResources().getString(R.string.empty));
		}
	}

	// this variant use for imgEditPhone can change to SaveEditted

	public void getEvent() {

		imgEditPhone.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (checkClick == 1) {
					tvNameProfile.setVisibility(View.GONE);
					layoutEditName.setVisibility(View.VISIBLE);
					tvPhoneProfile.setVisibility(View.GONE);
					layoutEditPhone.setVisibility(View.VISIBLE);
					imgEditPhone.setImageResource(R.drawable.save);
					edtEditPhone.setFocusable(true);
					edtEditPhone.requestFocus();
					checkClick = 0;

				} else {

					/**
					 * update phonenumber and name from edtEditPhone and
					 * edtEditName
					 */
					if (!edtEditPhone.getText().toString().equals("")) {
						item.setPhoneNumber(edtEditPhone.getText().toString());
						db.updateBlackListItem(item, BlackListItem.ID + " = "
								+ item.getId(), null);
						tvPhoneProfile.setText(edtEditPhone.getText()
								.toString());
						edtEditPhone.setText(tvPhoneProfile.getText()
								.toString());
					}
					if (!edtEditName.getText().toString().equals("")) {
						item.setName(edtEditName.getText().toString());
						db.updateBlackListItem(item, BlackListItem.ID + " = "
								+ item.getId(), null);
						tvNameProfile.setText(edtEditName.getText());
						edtEditName.setText(tvNameProfile.getText());
					}

					imgEditPhone.setImageResource(R.drawable.imgedit);
					tvNameProfile.setVisibility(View.VISIBLE);
					layoutEditName.setVisibility(View.GONE);
					tvPhoneProfile.setVisibility(View.VISIBLE);
					layoutEditPhone.setVisibility(View.GONE);

					checkClick = 1;
				}
			}
		});
		btnLastBlocked.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (posInViewFlipper != 1) {

					btnModeCall
							.setBackgroundResource(softtech.apps.callblocker.R.drawable.frame);
					btnLastBlocked
							.setBackgroundResource(softtech.apps.callblocker.R.drawable.frame_press);
					btnModeSms
							.setBackgroundResource(softtech.apps.callblocker.R.drawable.frame);

					if (posInViewFlipper == 2) {
						adapterCallMode = null;
						viewFlipper.setInAnimation(ActivityContactProfile.this,
								R.anim.in_from_left);
						viewFlipper.setOutAnimation(
								ActivityContactProfile.this,
								R.anim.out_to_right);
						viewFlipper.showPrevious();
					} else {
						adaperSmsMode = null;
						viewFlipper.setInAnimation(ActivityContactProfile.this,
								R.anim.in_from_left);
						viewFlipper.setOutAnimation(
								ActivityContactProfile.this,
								R.anim.out_to_right);
						viewFlipper.showNext();
					}
					posInViewFlipper = 1;

				}
			}
		});
		btnModeCall.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (posInViewFlipper != 2) {
					/**
					 * set adapter for lvModeCall
					 */
					adaperSmsMode = null;
					adapterCallMode = new AdapterCallMode(
							ActivityContactProfile.this, item.getMode());
					lvModeCall.setAdapter(adapterCallMode);

					btnModeCall
							.setBackgroundResource(softtech.apps.callblocker.R.drawable.frame_press);
					btnLastBlocked
							.setBackgroundResource(softtech.apps.callblocker.R.drawable.frame);
					btnModeSms
							.setBackgroundResource(softtech.apps.callblocker.R.drawable.frame);

					if (posInViewFlipper == 1) {
						viewFlipper.setInAnimation(ActivityContactProfile.this,
								R.anim.in_from_right);
						viewFlipper
								.setOutAnimation(ActivityContactProfile.this,
										R.anim.out_to_left);
						viewFlipper.showNext();
					} else {
						viewFlipper.setInAnimation(ActivityContactProfile.this,
								R.anim.in_from_left);
						viewFlipper.setOutAnimation(
								ActivityContactProfile.this,
								R.anim.out_to_right);
						viewFlipper.showPrevious();
					}

					posInViewFlipper = 2;
				}

			}
		});
		btnModeSms.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (posInViewFlipper != 3) {

					/**
					 * set adapter for lvSmsMode
					 */
					adapterCallMode = null;
					adaperSmsMode = new AdapterSmsMode(
							ActivityContactProfile.this, item.getMode());
					lvModeSms.setAdapter(adaperSmsMode);

					/**
					 * set background for button
					 */
					btnModeCall
							.setBackgroundResource(softtech.apps.callblocker.R.drawable.frame);
					btnLastBlocked
							.setBackgroundResource(softtech.apps.callblocker.R.drawable.frame);
					btnModeSms
							.setBackgroundResource(softtech.apps.callblocker.R.drawable.frame_press);

					if (posInViewFlipper == 2) {
						viewFlipper
								.setOutAnimation(ActivityContactProfile.this,
										R.anim.out_to_left);
						viewFlipper.setInAnimation(ActivityContactProfile.this,
								R.anim.in_from_right);
						viewFlipper.showNext();
					} else {
						viewFlipper.setInAnimation(ActivityContactProfile.this,
								R.anim.in_from_left);
						viewFlipper.setOutAnimation(
								ActivityContactProfile.this,
								R.anim.out_to_right);
						viewFlipper.showPrevious();
					}
					posInViewFlipper = 3;
				}

			}
		});

		imgCallBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				showAlertDialog(
						mContext.getResources().getString(
								R.string.title_alert_dialog1),
						mContext.getResources().getString(
								R.string.message_alert_dialog1), item
								.getPhoneNumber(), 1);
			}
		});

		imgSendBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				showAlertDialog(
						mContext.getResources().getString(
								R.string.title_alert_dialog1),
						mContext.getResources().getString(
								R.string.message_alert_dialog2), item
								.getPhoneNumber(), 2);
			}
		});
		lvModeSms.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				int newMode = (item.getMode() & 240) | (position + 1);
				Log.i(TAG, "newMode: " + newMode + " " + (item.getMode() & 240)
						+ " modecu :" + item.getMode());
				item.setMode(newMode);
				adaperSmsMode = new AdapterSmsMode(ActivityContactProfile.this,
						newMode);
				lvModeSms.setAdapter(adaperSmsMode);
				db.updateBlackListItem(item,
						BlackListItem.ID + " = " + item.getId(), null);
				List<BlackListItem> l = db.getBlackListItem(null,
						BlackListItem.ID + " = " + item.getId(), null, null,
						null);
			}
		});
		lvModeCall.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				int newMode = (item.getMode() & 15) | ((position + 1) << 4);
				Log.i(TAG, "newmode: " + newMode);
				item.setMode(newMode);
				adapterCallMode = new AdapterCallMode(
						ActivityContactProfile.this, newMode);
				lvModeCall.setAdapter(adapterCallMode);
				db.updateBlackListItem(item,
						BlackListItem.ID + " = " + item.getId(), null);
				List<BlackListItem> l = db.getBlackListItem(null,
						BlackListItem.ID + " = " + item.getId(), null, null,
						null);
			}
		});
	}

	public void showAlertDialog(String title, String message,
			String numberPhone, final int what) {
		AlertDialog.Builder b = new AlertDialog.Builder(mContext);
		b.setTitle(title);
		b.setMessage(message);

		b.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				dialog.cancel();
			}
		});

		b.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				if (what == 1) {
					CallBack();

				} else {
					openChatActivity();
				}

			}
		});

		b.show();
	}

	/**
	 * method open ActivityChat - have add phonenumber and name of this item
	 */
	public void openChatActivity() {

		Intent i = new Intent(ActivityContactProfile.this, ActivityChat.class);
		i.putExtra("phonenumber", item.getPhoneNumber());
		i.putExtra("name", item.getName());
		startActivity(i);
		ActivityContactProfile.this.finish();
	}

	/**
	 * method to recall number of this item profile
	 */
	public void CallBack() {
		Intent callIntent = new Intent(Intent.ACTION_CALL);
		callIntent.setData(Uri.parse("tel:" + item.getPhoneNumber()));
		ActivityContactProfile.this.startActivity(callIntent);
	}

	/**
	 * Broadcast update view when have event
	 */
	final BroadcastReceiver broadcastUpdateForm = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.e(TAG, "NHAN DC EXTRA");
			Bundle bundleMessageData = intent.getExtras();
			if (bundleMessageData != null) {
				try {

					int haveSms = bundleMessageData
							.getInt(ApplicationConstants.TAG_BROADCAST);

					if (haveSms == 1) {
						String phone = bundleMessageData
								.getString(SmsBlockedItem.PHONE_NUMBER);
						if (phone.contentEquals(item.getPhoneNumber())) {
							String last_out_date = "";
							Calendar cal = Calendar.getInstance();
							SimpleDateFormat sdf = new SimpleDateFormat(
									"yyyy-MM-dd HH:mm:ss");
							last_out_date = sdf.format(cal.getTime());
							tvTimeSmsBlocked.setText(last_out_date);
						}

					}
					if (haveSms == 2) {
						String phone = bundleMessageData
								.getString(SmsBlockedItem.PHONE_NUMBER);
						if (phone.contentEquals(item.getPhoneNumber())) {
							String last_out_date = "";
							Calendar cal = Calendar.getInstance();
							SimpleDateFormat sdf = new SimpleDateFormat(
									"yyyy-MM-dd HH:mm:ss");
							last_out_date = sdf.format(cal.getTime());

							tvTimeCallBlocked.setText(last_out_date);
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}
	};

	public void showAlertDialog(String title, String message) {
		AlertDialog.Builder b = new AlertDialog.Builder(mContext);
		b.setTitle(title);
		b.setMessage(message);

		b.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});

		b.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				deleteProFile();
			}
		});

		b.show();
	}

	@Override
	public void onBackPressed() {

		super.onBackPressed();
		Intent intent = new Intent(this, ActivityShowBlackListItem.class);
		startActivity(intent);
		ActivityContactProfile.this.finish();
	}

	@Override
	protected void onResume() {

		super.onResume();
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();
	}

}
